// 决算录入弹窗
<template>
  <div class="addDialog basic-from" :class="{previewPage: isReadonly}">
    <el-dialog
      custom-class="small-padding-dialog"
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="1200px"
      @close="handleDialogClosed"
    >
      <div class="dialogWrap">
        <el-form ref="dialogForm" :rules="rules" :model="formData" class="form-wrap">
          <h4 class="dialogItemTitle full">结算信息</h4>
          <el-form-item label="工程名称" prop="engineeringName" class="listFormItem">
            <el-button type="primary" class="add" size="mini" @click="chooseEngineering" v-if="!isReadonly">选择工程</el-button>
            <el-input v-halfCharCode v-model="formData.engineeringName" readonly />
          </el-form-item>
          <el-form-item label="物业名称" prop="propertyName">
            <el-input v-halfCharCode v-model="formData.propertyName" readonly />
          </el-form-item>
          <h4 class="full">结算情况</h4>
          <el-form-item label="结算审核日期" prop="settlementTm">
            <el-date-picker
              v-model="formData.settlementTm"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              type="datetime"
              placeholder="请选择结算日期"
              :readonly="isReadonly"
							:picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item label="送审金额" prop="censorshipAmount">
            <el-input v-halfCharCode v-model="formData.censorshipAmount" maxlength="15" v-if="!isReadonly" placeholder="请输入送审金额" />
            <el-input :value="formData.censorshipAmount | thousandMoney" readonly v-else />
          </el-form-item>

          <el-form-item label="审定金额" prop="approvalAmount">
            <el-input v-halfCharCode v-model="formData.approvalAmount" maxlength="15" v-if="!isReadonly" placeholder="请输入审定金额" />
            <el-input :value="formData.approvalAmount | thousandMoney" readonly v-else />
          </el-form-item>

          <el-form-item label="核减金额" prop="reductionAmount">
            <el-input :value="formData.reductionAmount | thousandMoney" disabled maxlength="15" placeholder="请输入核减金额" />
          </el-form-item>

          <el-form-item label="核减率" prop="subtractRate">
            <el-input v-model="formData.subtractRate" disabled maxlength="15" placeholder="请输入核减率" />
          </el-form-item>
          <el-form-item label="审核公司" prop="auditCompany">
            <el-input v-halfCharCode v-model="formData.auditCompany" maxlength="15" :readonly="isReadonly" placeholder="请输入审核公司" />
          </el-form-item>
          <h4 class="full">上传附件</h4>
          <el-form-item class="full">
            <v-upload
              type="file"
              ref="upload"
              :busId="formData.conclusionId"
              modelType="finalAccounts"
              v-if="dialogVisible"
              @onSuccess="onSuccess"
              multiple
              :isView="['preview'].includes(type)"
              v-model="fileList"
            />
          </el-form-item>
        </el-form>
        <!-- 工程选择弹窗 -->
        <propertyChooseDialog ref="engineeringChoose" dialogType="final-accounts" @changeProperty="handleEngineeringChange" />
      </div>
      <div slot="footer">
        <el-button @click="$bus.$emit('operationLog',formData.obtId)" v-if="type==='preview'">操作日志</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]" :loading="saveLoading">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import { changeConclusion } from "@/views/wy-operate/api/repair";
import { calc } from '@/utils'
export default {
  name: 'addDepartment',
  components: {
    propertyChooseDialog,
  },
  inject: ['initList'],
  data () {
    return {
      fileList: [], //上传列表
      type: 'add',//弹窗类型，默认新增
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        //结算ID
        conclusionId: '',
        //预算ID
        obtId: '',
        //房源ID
        roomId: '',
        //工程名称
        engineeringName: '',
        // 物业名称
        propertyName: '',
        // 结算日期
        settlementTm: '',
        // 送审金额(结算)
        censorshipAmount: '',
        // 审定金额(结算)
        approvalAmount: '',
        // 核减金额(结算)
        reductionAmount: '',
        // 核减率(结算)
        subtractRate: '',
        // 审核公司(结算)
        auditCompany: '',
        //工单id
        billId: '',
      },
      // 校验规则
      rules: {
        engineeringName: [{ required: true, message: "工程名称不能为空", trigger: "blur" }],
        propertyName: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
        settlementTm: [{ required: true, message: "结算日期不能为空", trigger: "blur" }],
        censorshipAmount: [
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: "请输入正确的金额", trigger: "blur" },
        ],
        approvalAmount: [
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: "请输入正确的金额", trigger: "blur" },
        ],
        reductionAmount: [
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: "请输入正确的金额", trigger: "blur" },
        ],
      },
      // 保存按钮loading
      saveLoading: false,

			pickerOptions: {
				disabledDate:function disabledDate(time){
					//return time.getTime() < Date.now() // 选当前时间之后的时间
					return time.getTime() > Date.now() // 选当前时间之前的时间
				}
			}
    }
  },
  computed: {
    // 弹窗标题计算
    dialogTitle () {
      return {
        'preview': '查看',
        'edit': '编辑',
        'add': '新增'
      }[this.type]
    },
    // 判断是否只读
    isReadonly () {
      return ["preview"].includes(this.type);
    },
  },
  watch: {
    //送审金额
    'formData.censorshipAmount': function (val) {
      //核减金额
      let reductionAmount = calc.Sub(Number(val), Number(this.formData.approvalAmount))
      this.formData.reductionAmount = reductionAmount || 0
      // 核减率
      let subtractRate = calc.Div(Number(reductionAmount), Number(val))
      this.formData.subtractRate = subtractRate ? (subtractRate * 100).toFixed(2) + '%' : '0%'
    },
    //审定金额
    'formData.approvalAmount': function (val) {
      //核减金额
      let reductionAmount = calc.Sub(Number(this.formData.censorshipAmount), Number(val))
      this.formData.reductionAmount = reductionAmount || 0
      // 核减率
      let subtractRate = calc.Div(Number(reductionAmount), Number(this.formData.censorshipAmount))
      this.formData.subtractRate = subtractRate ? (subtractRate * 100).toFixed(2) + '%' : '0%'
    }
  },
  methods: {
    onSuccess (response, file, fileList) {
      this.saveLoading = true
      let params = this.type == 'add' ? { ...this.formData, conclusionId: response.data } : this.formData
      changeConclusion(params, this.type).then(res => {
        if (res.data.code == 0) {
          this.$message.success(`${this.dialogTitle}成功!`);
          this.initList({ current: 1, size: 20, queryConditions: "" });
          this.dialogVisible = false;
        } else {
          this.$message.error(res.data.msg)
        }
      }).finally(() => {
        this.saveLoading = false
      })
    },
    //开启弹窗
    async show ({ type, data = {} }) {
      if (['preview', 'edit'].includes(type)) {
        const result = await this.http(`/api/conclusion/${data.conclusionId}`)
        this.formData = result.data.data;
      } else {
        this.formData = {}
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 提交新增
    save () {
      if (['edit', 'add'].includes(this.type)) {
        this.$refs.dialogForm.validate((valid) => {
          if (valid) {
            this.$refs.upload.submit('finalAccounts', this.formData.conclusionId);
          }
        });
      }
    },
    // 选择工程名称
    chooseEngineering () {
      this.$refs.engineeringChoose.show("final-accounts");
    },
    // 监听工程改变
    handleEngineeringChange (data) {
      this.formData = {
        ...this.formData,
        engineeringName: data.engineeringName,
        propertyName: data.propertyName,
        censorshipAmount: data.totalAmount,
        approvalAmount: data.totalAmount,
        obtId: data.obtId,
        roomId: data.roomId,
        billId: data.billId,
      };
    },
    // 监听弹窗关闭
    handleDialogClosed () {
      for (var i in this.formData) {
        this.formData[i] = ''
      }
      this.$refs.dialogForm.resetFields()
    },


  },
}
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.addDialog {
  /deep/ .el-date-editor--datetime {
    width: 100%;
  }
}
</style>
